﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.SemanticSemproxySearchResponse.Types;

namespace Admin.NET.Application
{
    /// <summary>
    /// 广宇接口
    /// </summary>
    [ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
    public class GuangYu : IDynamicApiController, ITransient
    {

        private readonly SqlSugarRepository<BanZu> _banZuRep;
        private readonly SqlSugarRepository<Employee> _employeeRep;
        private readonly SqlSugarRepository<PaiBan> _paiBanRep;
        private readonly SqlSugarRepository<UploadLog> _uploadLogRep;
        private readonly SqlSugarRepository<Device> _deviceRep;

        public GuangYu(SqlSugarRepository<BanZu> banZuRep, SqlSugarRepository<Employee> employeeRep, SqlSugarRepository<UploadLog> uploadLogRep, SqlSugarRepository<Device> deviceRep)
        {
            _banZuRep = banZuRep;
            _employeeRep = employeeRep;
            _uploadLogRep = uploadLogRep;
            _deviceRep = deviceRep;
        }

        /// <summary>
        /// 分页查询班组列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("/other/Team/page")]
        [AllowAnonymous]
        public async Task<List<BanZu>> TeamPage([FromQuery] OtherQueryPara input)
        {
            if (input.ProjectId == 0)
            {
                throw Oops.Oh("项目ID不明确");
            }
            if (string.IsNullOrEmpty(input.Token) || input.Token != "qa8XTPa895123x")
            {
                throw Oops.Oh("Token不正确");
            }
            var banZuRep = await _banZuRep.AsQueryable()
                                     .ClearFilter()
                                     .WhereIF(input.ProjectId > 0, u => u.ProjectId == input.ProjectId)
                                     .ToListAsync();
            return banZuRep;
        }

        /// <summary>
        /// 查询人员列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("/other/Employee/page")]
        [AllowAnonymous]
        public async Task<List<OtherEmployeeOutput>> OtherPage([FromQuery] OtherQueryPara input)
        {
            if (input.ProjectId == 0)
            {
                throw Oops.Oh("项目ID不明确");
            }
            if (string.IsNullOrEmpty(input.Token) || input.Token != "qa8XTPa895123x")
            {
                throw Oops.Oh("Token不正确");
            }
            var employees = await _employeeRep.AsQueryable()
                                     .ClearFilter()
                                     .WhereIF(input.ProjectId > 0, u => u.ProjectId == input.ProjectId)
                                     .Select<OtherEmployeeOutput>()
                                     .ToListAsync();
            try
            {
                if (employees != null)
                {
                    foreach (var item in employees)
                    {
                        var paiBanList = await _paiBanRep.AsQueryable()
                            .ClearFilter()
                            .Where(u => u.EmployeeId == item.Id)
                            .Select<PaiBanOutPut>()
                            .ToListAsync();
                        if (paiBanList != null && paiBanList.Count > 0)
                        {

                            foreach (var itemA in paiBanList)
                            {
                                if (itemA.EndTime?.ToString("yyyy-MM-dd HH:mm:ss") == "0001-01-01 23:59:59")
                                {
                                    itemA.EndTime = null;
                                }
                                var paiban = _banZuRep
                                    .AsQueryable()
                                    .ClearFilter()
                                    .FirstAsync(u => u.CreateOrgId == itemA.CreateOrgId && u.TeamName == itemA.WorkGroup);
                                if (paiban != null) { itemA.PaiBanId = paiban.Id; };
                            }
                            item.PaiBanList = paiBanList;
                        }
                    }

                }
            }
            catch (Exception e)
            {

                await Console.Out.WriteLineAsync(e.Message + e.StackTrace);
            }

            return employees;
        }

        /// <summary>
        /// 分页查询通行记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("/other/UploadLog/page")]
        [AllowAnonymous]
        public async Task<List<OtherUploadLogOutput>> LogPage([FromQuery] OtherQueryPara input)
        {
            if (input.ProjectId == 0)
            {
                throw Oops.Oh("项目ID不明确");
            }
            if (string.IsNullOrEmpty(input.Token) || input.Token != "qa8XTPa895123x")
            {
                throw Oops.Oh("Token不正确");
            }

            if (input.StartTime == null || input.EndTime == null)
            {
                throw Oops.Oh("时间段不正确");
            }

            //取某一天的最后一刻（即 23:59:59.9999999）
            //input.EndTime.Value.Date.AddDays(1).AddTicks(-1))
            //input.EndTime.Value  进行解包的操作,用来获取其非空值
            //input.EndTime.Value.Date Date 属性返回 DateTime 的日期部分，并将时间部分设为 00:00:00,即2024-09-03 00:00:00
            //AddDays(1) 将日期加一天
            //AddTicks(-1) AddTicks(-1) 将从前一步骤的日期时间中减去一个刻度（tick）。1 tick 是 100 纳秒,变为 2024-09-03 23:59:59.9999999
            var uploadLogs = await _uploadLogRep.AsQueryable()
            .ClearFilter()
                .Where(u => u.ProjectId == input.ProjectId)
                .Where(u => SqlFunc.ToDate(u.cap_time) >= input.StartTime)
                .Where(u => SqlFunc.ToDate(u.cap_time) <= input.EndTime.Value.Date.AddDays(1).AddTicks(-1))
                .Select<OtherUploadLogOutput>()
                .ToListAsync();


            foreach (var item in uploadLogs)
            {
                var device = await _deviceRep.AsQueryable()
                   .ClearFilter()
                   .Where(u => u.ClientSn == item.ClientSn)
                   .FirstAsync();

                if (device != null) item.Direction = device.Direction;
            }
            return uploadLogs;
        }
    }
}

public class OtherQueryPara
{
    //public string ClientSn { get; set; }
    //public string EmpName { get; set; }
    [Required(ErrorMessage = "项目ID是必须的")]
    public long? ProjectId { get; set; }
    [Required(ErrorMessage = "Token是必须的")]
    public string? Token { get; set; }
    // 开始时间
    public DateTime? StartTime { get; set; }
    // 结束时间
    public DateTime? EndTime { get; set; }

    //public bool? IsUpload { get; set; }
    //public bool? IsMobile { get; set; }
}

/// <summary>
/// 通行记录输出参数
/// </summary>
public class OtherUploadLogOutput
{
    /// <summary>
    /// 项目Id
    /// </summary>
    public long ProjectId { get; set; }

    /// <summary>
    /// 项目名称
    /// </summary>
    public string ProjectName { get; set; }

    /// <summary>
    /// 客户端设备号
    /// </summary>
    public string ClientSn { get; set; }

    /// <summary>
    /// 平台ID
    /// </summary>
    public string EmpID { get; set; }

    /// <summary>
    /// 自定义的字段信息，用于UUID
    /// </summary>
    public string customer_text { get; set; }

    /// <summary>
    /// 抓拍时间
    /// </summary>
    public string cap_time { get; set; }

    /// <summary>
    /// 人员姓名
    /// </summary>
    public string EmpName { get; set; }

    /// <summary>
    /// 通行方向
    /// </summary>
    public DirectionType Direction { get; set; } = DirectionType.@in;
}

/// <summary>
/// 人员列表输出参数
/// </summary>
public class OtherEmployeeOutput
{

    /// <summary>
    /// 组织ID
    /// </summary>
    public long OrgId { get; set; }

    /// <summary>
    /// 记录ID
    /// </summary>
    public long Id { get; set; }

    /// <summary>
    /// 姓名
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 项目Id
    /// </summary>
    public long ProjectId { get; set; }

    /// <summary>
    /// 人员UID
    /// </summary>
    public string EmpGuid { get; set; }

    /// <summary>
    /// 身份证号
    /// </summary>
    public string IdNum { get; set; }

    ///// <summary>
    ///// 工作组
    ///// </summary>
    //public virtual string Work_TypeName { get; set; }

    /// <summary>
    /// 人员排班表
    /// </summary>
    public List<PaiBanOutPut> PaiBanList { get; set; } = new List<PaiBanOutPut>();

}

/// <summary>
/// 排班表
/// </summary>
public class PaiBanOutPut : EntityTenantBaseData
{
    /// <summary>
    /// 人员ID
    /// </summary>
    public long EmployeeId { get; set; }

    //开始时间
    public DateTime StartTime { get; set; }

    //结束时间
    public DateTime? EndTime { get; set; }

    //工作组 workgroup
    public string WorkGroup { get; set; }

    /// <summary>
    /// 班次ID
    /// </summary>
    public long PaiBanId { get; set; }
}
